import { MessagePlugin } from 'tdesign-vue-next';
import { isJSON, isURL } from 'validator';

import router from '@/router';

/**
 * 判断地址是否为IP
 * @param hostname
 */
export function isIPAddress(hostname: string): boolean {
  // 定义 IP 地址的正则表达式
  const ipRegex = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;

  // 判断给定的域名是否符合 IP 地址的格式
  return ipRegex.test(hostname);
}

/**
 * 是否来自设备
 */
export function isDeviceExport() {
  return isIPAddress(window.location.hostname);
}

/**
 * 获取路径
 * @param path
 */
export function getPath(path: string): String {
  return `/#${path}`;
}

/**
 * 打开首页
 */
export function goHome(): void {
  // @ts-ignore
  router.push(getPath('/'));
}

/**
 * 显示消息
 *
 * @param msg
 * @param type
 */
export function showMessage(msg: string, type: string = 'success'): void {
  if (type === 'error') {
    MessagePlugin.error({ content: msg, placement: 'top-right' });
  } else if (type === 'warning') {
    MessagePlugin.warning({ content: msg, placement: 'top-right' });
  } else {
    MessagePlugin.success({ content: msg, placement: 'top-right' });
  }
}

/**
 * 深Copy
 * @param obj
 */
export function steveDeepCopy<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj)) as T;
}

export function deepMerge<T extends object>(obj1: T, obj2: Partial<T>): T {
  const merged = { ...obj1, ...obj2 };
  return steveDeepCopy(merged);
}

/**
 * 根据路径获取值
 * @param obj 目标对象
 * @param path 路径 a.b.c
 */
export function getValueByPath(obj: any, path: string): any {
  const pathParts = path.split('.');
  let currentLevel = obj;
  for (const part of pathParts) {
    if (currentLevel && Object.prototype.hasOwnProperty.call(currentLevel, part)) {
      currentLevel = currentLevel[part];
    } else {
      return '';
    }
  }
  return currentLevel;
}

/**
 * 根据路径将值写入
 * @param obj 目标对象
 * @param path 路径 a.b.c
 * @param value 写入的值
 */
export function setValueByPath(obj: any, path: string, value: any): void {
  const pathParts = path.split('.');
  const lastKey = pathParts.pop();
  let currentLevel = obj;

  pathParts.forEach((part) => {
    if (currentLevel[part] == null) {
      currentLevel[part] = {};
    }
    currentLevel = currentLevel[part];
  });
  currentLevel[lastKey] = value;
}

/**
 * 获取对象的路径数组
 * @param obj
 * @param path
 * @param list
 */
export function getObjectPaths(obj: any, path: string = '', list: any = []): any {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const newPath = path ? `${path}.${key}` : key;
      const value = obj[key];

      if (typeof value === 'object' && Object.keys(value).length) {
        // 如果值是对象或数组，递归遍历
        getObjectPaths(value, newPath, list);
      } else {
        let type;
        if (Array.isArray(value)) {
          type = 'array';
        } else {
          type = typeof value;
        }
        list.push({
          type,
          value: newPath,
          defaultValue: value,
        });
      }
    }
  }
  return list;
}

/**
 * JSON格式化
 * @param value
 */
export function formatJSON(value: string) {
  try {
    value = JSON.stringify(JSON.parse(value), null, 4);
  } catch (e) {
    value = '';
  }
  return value;
}

/**
 * JSON压缩
 * @param value
 */
export function compressJSON(value: string) {
  try {
    value = JSON.stringify(JSON.parse(value));
  } catch (e) {
    value = '';
  }
  return value;
}

/**
 * 打开url地址
 * @param url
 */
export function openURL(url: string) {
  window.open(url, '_blank');
}

/**
 * 判断对象是否为空
 * @param value
 */
export function isObjectEmpty(value: any) {
  let bool = false;
  if (typeof value === 'object') {
    bool = Object.keys(value).length === 0;
  } else if (Array.isArray(value)) {
    bool = value.length === 0;
  } else if (typeof value === 'string') {
    if (isJSON(value)) {
      isObjectEmpty(JSON.parse(value));
    }
  }
  return bool;
}

/**
 * Html转规则
 */
export function htmlToRules(value: string) {
  if (!value) {
    return [];
  }
  try {
    const arr = value.match(/<(a|option)[\s\S]*?(href|value)\s*?=\s*?["'][\s\S]*?["'][\s\S]*?>[\s\S]*?<\/(a|option)>/g);
    const cate = [];
    for (let i = 0; i < arr.length; i++) {
      // 正则除span标签、div标签
      const tmp = arr[i].replace(/<(span.*?|\/span|div.*?|\/div)>/g, '');
      const list = tmp.match(
        /<(a|option)[\s\S]*?(href|value)\s*?=\s*?["']([\s\S]*?)["'][\s\S]*?>([\s\S]*?)<\/(a|option)>/,
      );
      const path = list[3].trim().replaceAll('&amp;', '&');
      // console.log(path);
      cate.push({
        name: removeHtmlUsingDomParser(list[4].trim()),
        path,
        value: path,
      });
    }
    return cate;
  } catch (e) {
    return [];
  }
}

/**
 * 字符串转正则
 *
 * @param pattern
 */
export function convertStringToRegex(pattern: string): RegExp {
  const regexPattern = pattern.replace(/\?/, '\\?').replace(/@{(.*?)}/g, '(.*)').replace(/\s/g, '');
  return new RegExp(`^${regexPattern}$`);
}

/**
 * 删除html
 *
 * @param html
 */
export function removeHtmlUsingDomParser(html: string): string {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  return doc.body.textContent || '';
}

/**
 * 删除url的host
 *
 * @param url
 */
export function urlToPath(url: string) {
  let newUrl = url;
  if (isURL(url)) {
    const parsedUrl = new URL(url);
    const { pathname, search } = parsedUrl;
    newUrl = `${pathname}${search}`;
  }
  return decodeURIComponent(newUrl);
}

/**
 * 获取数组中某个字段转换成新的数组
 */
export function getArrayFieldToArray(arr: any, field: string) {
  const newArr = [];
  for (const a of arr) {
    if (a[field]) {
      newArr.push(a[field]);
    }
  }
  return newArr;
}
